package com.smart.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.smart.dao.UserDao;
import com.smart.dao.UserExtendDao;
import com.smart.dao.UserRoleDao;
import com.smart.domain.Role;
import com.smart.domain.User;
import com.smart.domain.UserExtend;
import com.smart.domain.UserRole;
import com.smart.dto.RegisterDto;
import com.smart.dto.UserDto;
import com.smart.service.UserService;
import com.smart.tools.DESHelper;
import com.smart.tools.DateHelper;
import com.smart.tools.MessageException;
import com.smart.tools.ObjectHelper;
import com.smart.tools.SendEmailMsg;
import com.smart.tools.SendSMSMsg;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	UserDao userDao;

	@Autowired
	UserRoleDao userRoleDao; 
	
	@Autowired
	UserExtendDao userExtendDao;
	
	@Override
	public User findByUserId(String id) throws Exception {
		
		return userDao.getEntity(id);
	}

	@Override
	public User findbyCons(Map<String, Object> conditions) throws Exception {
		List<User>  users = userDao.queryUser(conditions);
		if(ObjectHelper.isNotEmpty(users) && users.size() != 0){
			return users.get(0);
		}
		return null;
	}

	@Override
	@Transactional
	public void register(RegisterDto registerDto) throws Exception {
		if(ObjectHelper.isEmpty(registerDto)){
			throw new MessageException("注册信息为空");
		}
		if(ObjectHelper.isEmpty(registerDto.getPhoneNumber())){
			throw new MessageException("手机号不能为空");
		}
		
		if(ObjectHelper.isEmpty(registerDto.getRole())){
			throw new MessageException("系统角色不能为空");
		}
		
		//验证确认密码与密码是否一致
		if(!registerDto.getPassword().equals(registerDto.getConfrimPassword())){
			throw new MessageException("确认密码不一致");
		}
		
		//判断用户注册 如果物业注册需审核 ，业主注册无需审核直接通过
		String status = registerDto.getRole();
		if(Role.ROLE_CODE_PM.equals(registerDto.getRole())){
			status = User.USER_STATUS_EV;
		}else{
			status = User.USER_STATUS_NORMAL;
		}
		
		//保存注册信息
		User user = new User();
		user.setUserName(registerDto.getUserName());
		user.setPhoneNumber(registerDto.getPassword());
		user.setRegisterTime(DateHelper.dateToString(new Date()));
		DESHelper desKey = DESHelper.getInstance(user.getRegisterTime());
		user.setPassword(desKey.encrypt(registerDto.getPassword()));
		user.setEmail(registerDto.getEmail());
		user.setStatus(status);
		user = userDao.saveEntity(user);
		
		//保存角色信息
		UserRole userRole = new UserRole();
		userRole.setUserId(user.getId());
		userRole.setRoleId(registerDto.getRole());
		userRoleDao.saveEntity(userRole);
	}

	@Override
	@Transactional
	public void resestPassword(String userId, String password) throws Exception {
		//查询用户信息
		User user = userDao.getEntity(userId);
		
		//秘钥   注册时间 如果注册时间为空123456
		DESHelper desKey = DESHelper.getInstance(ObjectHelper.isNotEmpty(user.getRegisterTime())?user.getRegisterTime():"123456");
		user.setPassword(desKey.encrypt(password));
		userDao.updateEntity(user);
	}


	@Override
	@Transactional
	public UserDto updateUser(UserDto userDto) throws Exception {
		if(ObjectHelper.isEmpty(userDto)  || ObjectHelper.isEmpty(userDto.getUserId())){
			throw new Exception("用户ID为空");
		}
		
		//修改用户信息
		User user = userDao.getEntity(userDto.getUserId());
		BeanUtils.copyProperties(userDto, user);
		userDao.updateEntity(user);
		
		//修改用户扩展信息
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("userId", userDto.getUserId());
		List<UserExtend> userExtends = userExtendDao.queryUserExtend(conditions);
		UserExtend userExtend = null;
		if(ObjectHelper.isNotEmpty(userExtends) && userExtends.size() != 0){
			userExtend = userExtends.get(0);
		}else{
			userExtend = new UserExtend();
		}
		
		BeanUtils.copyProperties(userDto, userExtend);
		userExtendDao.saveOrUpdateEntity(userExtend);
		
		return userDto;
	}
	
	@Override
	@Transactional
	public void updatePassword(String userId, String oldPassword, String password) throws Exception {
		//查询用户信息
		User user = userDao.getEntity(userId);
		//加密比较旧密码
		DESHelper desKey = DESHelper.getInstance(ObjectHelper.isNotEmpty(user.getRegisterTime())?user.getRegisterTime():"123456");
		String oldPasswordEncrypt = desKey.encrypt(oldPassword);
		if(!oldPasswordEncrypt.equals(user.getPassword())){
			throw new MessageException("旧密码输入错误");
		}
		//修改密码
		user.setPassword(desKey.encrypt(password));
		userDao.updateEntity(user);
	}

	@Override
	public String getValidateCode(String phoneNumber, String email ,String operate, String type) throws Exception {
		Random r = new Random();
		Integer i = r.nextInt(900000)+100000;
		String validateCode = DESHelper.getInstance("validateCode").encrypt(i+"");
		
		//发送内容
		String content = "";
		String title = SendSMSMsg.SIGNATURE;
		if("1".equals(operate)){
			title += "注册";
			content  += SendSMSMsg.SIGNATURE + "您的验证码是"+i+"，您正在注册xxx系统，如非本人操作请忽略";
		}else if("2".equals(operate)){
			title += "重置密码";
			content  += SendSMSMsg.SIGNATURE + "您的验证码是"+i+"，您正在重置密码，如非本人操作请忽略";
		}else if("3".equals(operate)){
			title += "修改密码";
			content  += SendSMSMsg.SIGNATURE + "您的验证码是"+i+"，您正在修改密码，如非本人操作请忽略";
		}
		
		if("SMS".equals(type)){
			//发送短信验证码
			SendSMSMsg.sendMsg(phoneNumber, content);
		}else if("EMAIL".equals(type)){
			//发送邮箱验证码
			SendEmailMsg.sendEmailMsg(email,title, content);
		}
		
		return validateCode;
	}

	

}
